package com.lagou.edu.factory;

import com.lagou.edu.anno.Autowired;

import javax.swing.text.Element;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @author HZF
 * @date 2020/5/27 20:58
 * description
 */
public class BeanFactoryAnno {

    //自定义通过注解获得getBean
    public static <Q> Q getBean(Class<Q> clazz){
        Q result = null;
        try{
            result = clazz.newInstance();
        }catch(InstantiationException e){
            e.printStackTrace();
            System.out.println("get the"+clazz.getName() + "failed!");
            return null;
        }catch(IllegalAccessException e){
            System.out.println("get the "+clazz.getName()+"failed!");
            e.printStackTrace();
            return null;
        }
        //查找所有的字段
        Field[] fields = clazz.getDeclaredFields();
        for(Field field : fields){//查找字段中含有依赖注入的字段，存在就进行注入
            Autowired inject = field.getAnnotation(Autowired.class);//自定义注解
            if(inject != null){
                Object object = getBean(field.getType());
                if(!field.isAccessible()){
                    field.setAccessible(true);
                }
                try{
                    field.set(result,object);
                }catch(IllegalAccessException e){
                    e.printStackTrace();
                    System.out.println("Inject the"+field.getName()+"failed!");

                }
            }
        }
        return result;
    }

}
